import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from './store'
import { changeActive, getChannelList } from './store/action/channel'
import { getNewsList } from './store/action/news'
import defaultCover from './assets/defaultCover.jpg'

export default function App() {

  return (
    <>
      {/* 头部频道 */}
      <Channel />
      {/* 文章列表 */}
      <Article />
    </>
  )
}

function Channel() {

  const dispatch = useDispatch()
  // 分模块后，state 需要指定为 RootState，包含所有模块 state
  const { list, active } = useSelector((state: RootState) => state.channel)
  // 组件挂载时
  useEffect(() => {
    // 发送请求获取频道数据(异步action)
    dispatch(getChannelList())
  }, [dispatch])

  return (
    <ul className='catagtory' >
      {list.map((item, index) => (
        <li
          key={item.id}
          className={active === index ? 'select' : ''}
          onClick={() => dispatch(changeActive(index))}
        >
          {item.name}
        </li>
      ))}


    </ul>
  )
}

function Article() {
  // 获取新闻列表
  const { list } = useSelector((state: RootState) => state.news)
  const { active } = useSelector((state: RootState) => state.channel)
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getNewsList(active))
  }, [dispatch, active])

  return (
    <div className='list'>
      {list.map(item => (
        <div key={item.art_id} className='article_item'>
          <h3 className='van-ellipsis'>{item.title}</h3>
          <div className='img_box'>
            <img src={item.cover.type === 0 ? defaultCover : item.cover.images[0]} className='w100' alt='' />
          </div>
          <div className='info_box'>
            <span>{item.aut_name}</span>
            <span>{item.comm_count}评论</span>
            <span>{item.pubdate}</span>
          </div>
        </div>
      ))}
    </div>
  )
}
